package org.springblade.common.utils;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class JpushTemplate {

    private static final String masterSecret = "66b2171ef858d7009d8b87c8";
    private static final String appKey = "d2364fb263409cdc9635c259";

    public static void pushMessage(String alert) {
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());
        PushPayload payload = PushPayload.alertAll(alert);
        try {
            //离线消息保留时间120秒
            payload.resetOptionsTimeToLive(120);
            PushResult result = jpushClient.sendPush(payload);
            log.info("result=" + JSON.toJSONString(result));
        } catch (APIConnectionException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static void pushMessage(List<String> userTags, String alert) {
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.registrationId(userTags))
                .setNotification(Notification.alert(alert))
                .setMessage(Message.newBuilder().setMsgContent(alert).build())
                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                .build();
        try {
            //离线消息保留时间120秒
            payload.resetOptionsTimeToLive(120);
            PushResult result = jpushClient.sendPush(payload);
            log.info("pushMessage=result=" + JSON.toJSONString(result));
        } catch (APIConnectionException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
    }


}
